package cn.wenlwan.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import netty.demo.echo.EchoClientHandler;

/**
 * creator: maokai
 * on: 2018/2/22
 * description:
 */
public class EchoClient {

    static final String HOST = System.getProperty( "host" , "127.0.0.1" );
    static final int PORT = Integer.parseInt( System.getProperty( "port" , "8080" ) );
    static final int SIZE = Integer.parseInt( System.getProperty( "size" , "256" ) );

    public void run () throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group( group);
            bootstrap.channel( NioSocketChannel.class )
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    p.addLast("decoder", new StringDecoder());
                    p.addLast("encoder", new StringEncoder());
                    p.addLast(new EchoClientHandler());
                }
            });

            // Start the client.
            ChannelFuture f = bootstrap.connect(HOST, PORT).sync();

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }

    }
    public  static void main(String [] args) throws InterruptedException {
        new EchoClient().run();

    }

}
